package com.joysuch.wwyt.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joysuch.wwyt.attendance.excel.AttendanceUserExcelService;
import com.joysuch.wwyt.common.constant.RiskEvaluationTemplateType;
import com.joysuch.wwyt.common.entity.CommonImportTemplate;
import com.joysuch.wwyt.common.enums.TemplateTypes;
import com.joysuch.wwyt.common.mapper.CommonImportTemplateMapper;
import com.joysuch.wwyt.common.service.CommonImportTemplateService;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.enums.DeleteFlag;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.dynamicdata.entity.BaseDynamicFieldConfig;
import com.joysuch.wwyt.dynamicdata.service.BaseDynamicFieldConfigService;
import com.joysuch.wwyt.patrol.service.PatrolCheckPointService;
import com.joysuch.wwyt.risk.service.RiskStorePointEvalExcelExportService;
import com.joysuch.wwyt.util.ZipDownloadUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author heqifeng
 * @since 2022-01-07
 */
@Service
@Slf4j
public class CommonImportTemplateServiceImpl extends ServiceImpl<CommonImportTemplateMapper, CommonImportTemplate> implements CommonImportTemplateService {

    @Autowired
    private CommonImportTemplateMapper mapper;
    @Autowired
    private BaseDynamicFieldConfigService fieldConfigService;
    @Autowired
    private RiskStorePointEvalExcelExportService riskEvaluationExcelExportService;
    @Autowired
    private PatrolCheckPointService patrolCheckPointService;
    @Autowired
    private AttendanceUserExcelService attendanceUserExcelService;

    @Override
    public void downLoadTemplate(HttpServletRequest request, HttpServletResponse response, Long templateId) {
        CommonImportTemplate template = getById(templateId);
        Integer templateCode = template.getTemplateCode();
        String fileName = TemplateTypes.getFileName(templateCode);
        if (StringUtils.isEmpty(fileName)) {
            throw new IllegalArgumentException("文件不存在");
        }
        String agent = request.getHeader("User-Agent");
        try {
            Workbook workbook = null;
            // 处理山东版和全国版的风险评估横/纵向模板
            if (RiskEvaluationTemplateType.riskPoint.equals(templateCode)) {
                // 风险点
                workbook = riskEvaluationExcelExportService.exportDistrictEvaluationExcel(0, null);
            }else if (RiskEvaluationTemplateType.riskPointStore.equals(templateCode)) {
                // 风险点库
                workbook = riskEvaluationExcelExportService.exportDistrictEvaluationExcel(0,1);
                //22为检查项目导入需要加入动态下拉列表
            }else if (TemplateTypes.CHECK_ITEM.getIndex().equals(templateCode)){
                workbook = patrolCheckPointService.exportCheckItemTem();
            }else if(TemplateTypes.ATTENDANCE_USER.getIndex().equals(templateCode)){
                 workbook = attendanceUserExcelService.exportUserExcel(0,null,null,null);
            }else {
                // 风险评估外的其他所有模板
                ClassPathResource classPathResource = new ClassPathResource("template" + File.separator + fileName);
                InputStream inputStream = classPathResource.getInputStream();
                workbook = WorkbookFactory.create(inputStream);
                // 动态字段
                if (StringUtils.isNotBlank(template.getTemplateBizType())) {
                    List<BaseDynamicFieldConfig> configList = fieldConfigService.findByBizType(template.getTemplateBizType());
                    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                        Sheet sheet = workbook.getSheetAt(i);
                        Row firstRow = sheet.getRow(sheet.getFirstRowNum());
                        int startNum = firstRow.getLastCellNum();
                        for (int j = startNum; j < startNum + configList.size(); j++) {
                            BaseDynamicFieldConfig config = configList.get(j - startNum);
                            CellStyle cellStyle = firstRow.getCell(startNum - 1).getCellStyle();
                            Cell newCell = firstRow.createCell(j);
                            newCell.setCellStyle(cellStyle);
                            newCell.setCellValue(config.getFieldDesc());
                        }
                    }
                }
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            workbook.write(baos);
            byte[] bytes = baos.toByteArray();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            if (agent.contains("MSIE")) {
                // IE浏览器
                fileName = URLEncoder.encode(fileName, "utf-8");
                fileName = fileName.replace("+", " ");
            } else {
                // 其它浏览器
                fileName = URLEncoder.encode(fileName, "utf-8");
            }
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            if (bytes.length != 0) {
                response.getOutputStream().write(bytes);
            } else {
                response.setStatus(404);
            }
            response.getOutputStream().flush();
        } catch (Exception e) {
            log.error("template down file error:{}" + e.getMessage());
        }
    }

    @Override
    public void downLoadTemplateBatch(HttpServletRequest request, HttpServletResponse response, List<Long> templateIds) throws IOException {
        ArrayList<byte[]> fileContent = new ArrayList<>();
        ArrayList<String> fileNames = new ArrayList<>();
        for (Long templateId : templateIds) {
            CommonImportTemplate template = getById(templateId);
            Integer templateCode = template.getTemplateCode();
            String fileName = TemplateTypes.getFileName(templateCode);
            // 处理山东版和全国版的风险评估横/纵向模板
            if (RiskEvaluationTemplateType.riskPoint.equals(templateCode)) {
                // 风险点
                Workbook riskWorkBook = riskEvaluationExcelExportService.exportDistrictEvaluationExcel(0, null);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                riskWorkBook.write(baos);
                byte[] bytes = baos.toByteArray();
                fileContent.add(bytes);
                fileNames.add(fileName);
                baos.close();
            }else if (RiskEvaluationTemplateType.riskPointStore.equals(templateCode)) {
                // 风险点库
                Workbook riskWorkBook = riskEvaluationExcelExportService.exportDistrictEvaluationExcel(0,1);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                riskWorkBook.write(baos);
                byte[] bytes = baos.toByteArray();
                fileContent.add(bytes);
                fileNames.add(fileName);
                baos.close();
            }else if (TemplateTypes.CHECK_ITEM.getIndex().equals(templateCode)){
                XSSFWorkbook workbook = patrolCheckPointService.exportCheckItemTem();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                workbook.write(baos);
                byte[] bytes = baos.toByteArray();
                fileContent.add(bytes);
                fileNames.add(fileName);
                baos.close();
            } else if(TemplateTypes.ATTENDANCE_USER.getIndex().equals(templateCode)){
                SXSSFWorkbook workbook = null;
                try {
                    workbook = attendanceUserExcelService.exportUserExcel(0,null,null,null);
                } catch (Exception e) {
                    if (e instanceof IllegalArgumentException){
                        throw new IllegalArgumentException(e.getMessage());
                    }
                }
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                workbook.write(baos);
                byte[] bytes = baos.toByteArray();
                fileContent.add(bytes);
                fileNames.add(fileName);
                baos.close();
            }else {
                // 风险评估以外的所有模板
                ClassPathResource classPathResource = new ClassPathResource("template" + File.separator + fileName);
                InputStream stream = classPathResource.getInputStream();
                // 动态字段,Workbook的create和write较慢，无动态字段时避免使用
                if (StringUtils.isNotBlank(template.getTemplateBizType())) {
                    Workbook workbook = WorkbookFactory.create(stream);
                    stream.close();
                    List<BaseDynamicFieldConfig> configList = fieldConfigService.findByBizType(template.getTemplateBizType());
                    for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
                        Sheet sheet = workbook.getSheetAt(i);
                        Row firstRow = sheet.getRow(sheet.getFirstRowNum());
                        int startNum = firstRow.getLastCellNum();
                        for (int j = startNum; j < startNum + configList.size(); j++) {
                            BaseDynamicFieldConfig config = configList.get(j - startNum);
                            CellStyle cellStyle = firstRow.getCell(startNum - 1).getCellStyle();
                            Cell newCell = firstRow.createCell(j);
                            newCell.setCellStyle(cellStyle);
                            newCell.setCellValue(config.getFieldDesc());
                        }
                    }
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    workbook.write(baos);
                    byte[] bytes = baos.toByteArray();
                    fileContent.add(bytes);
                    fileNames.add(fileName);
                    baos.close();
                }else {
                    if (stream != null) {
                        BufferedInputStream bufin = new BufferedInputStream(stream);
                        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
                        byte[] temp = new byte[1024];
                        int size = 0;
                        while ((size = bufin.read(temp)) != -1) {
                            out.write(temp, 0, size);
                        }
                        bufin.close();
                        stream.close();
                        byte[] content = out.toByteArray();
                        fileContent.add(content);
                        fileNames.add(fileName);
                    }
                }
            }
        }
        ZipDownloadUtil.downloadZip(response, "temlpates.zip", fileContent, fileNames);
    }

    @Override
    public IPage<CommonImportTemplate> pageTemplate(Integer pageNo,Integer size,String templateName) {
        LambdaQueryWrapper<CommonImportTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CommonImportTemplate::getDeleteFlag, DeleteFlag.EFFECTIVE.getCode());
        wrapper.eq(CommonImportTemplate::getOrgCode, Context.getCompanyCode());
        wrapper.eq(CommonImportTemplate::getTenentId, Context.getCurrentTenantId());
        wrapper.orderByAsc(CommonImportTemplate::getOrderNo);
        if (StringUtils.isNotBlank(templateName)) {
            wrapper.like(CommonImportTemplate::getName,templateName);
        }
        Page<CommonImportTemplate> page = new Page<>(pageNo+1,size);
        return mapper.selectPage(page, wrapper);
    }

    @Override
    public void checkDownloadTemplate(List<Long> templateIds) {
        for (Long templateId : templateIds) {
            CommonImportTemplate template = getById(templateId);
            Integer templateCode = template.getTemplateCode();
            if(TemplateTypes.ATTENDANCE_USER.getIndex().equals(templateCode)){
                SXSSFWorkbook workbook = null;
                try {
                    workbook = attendanceUserExcelService.exportUserExcel(0,null,null,null);
                } catch (Exception e) {
                    if (e instanceof IllegalArgumentException){
                        throw new IllegalArgumentException(e.getMessage());
                    }
                }
            }
        }
    }

}
